package com.zzyl.service.impl;

import com.zzyl.constant.Constants;
import com.zzyl.dto.CustomerLoginDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.CustomerLoginService;
import com.zzyl.service.MemberService;
import com.zzyl.service.WecharService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@Slf4j
public class CustomerLoginServiceImpl implements CustomerLoginService {
    @Autowired
    private WecharService wecharService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private JwtProperties jwtProp;
    /**
     * 处理用户登录请求。
     *
     * @param dto 包含用户登录所需信息的DTO（数据传输对象），例如微信Code和手机验证码。
     * @return LoginVo 包含登录成功后返回的token和用户昵称的信息。
     */
    @Override
    public LoginVo login(CustomerLoginDto dto) {
        // 通过微信服务获取用户的openId
        String openId = wecharService.getOpenId(dto.getCode());
        log.info("openId={}",openId);

        // 根据openId查询会员信息
        Member member = memberService.findByOpenId(openId);
        // 如果会员信息不存在，则新建一个会员记录
        if (member == null){
            member = new Member();
            member.setOpenId(openId);
        }

        // 通过微信服务获取用户的手机号
        String phoneNum = wecharService.getPhoneNum(dto.getPhoneCode());
        log.info("phoneNum={}",phoneNum);

        // 如果会员ID为空，设置会员的手机号和名字；如果手机号已存在且有变化，则更新会员信息
        if (member.getId() == null){
            member.setPhone(phoneNum);
            member.setName(phoneNum.substring(phoneNum.length()-4));
            memberService.insert(member);
        }else if (!member.getPhone().equals(phoneNum)){
            member.setPhone(phoneNum);
            memberService.update(member);
        }

        // 准备登录成功后返回的token所需信息
        HashMap<String, Object> map = new HashMap<>();
        map.put(Constants.JWT_USERID,member.getId());
        map.put(Constants.JWT_USERNAME,member.getName());

        // 生成并设置token
        String token = JwtUtil.createJWT(jwtProp.getBase64EncodedSecretKey(), jwtProp.getTtl(), map);
        LoginVo vo = new LoginVo();
        vo.setToken(token);
        vo.setNickName(member.getName());

        return vo;
    }

}
